package cn.lovingliu.chanma.controller;

import cn.lovingliu.chanma.form.DllCreateForm;
import cn.lovingliu.chanma.pojo.DllItem;
import cn.lovingliu.chanma.service.DllService;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author：LovingLiu
 * @Description:
 * @Date：Created in 2021-05-29
 */
@Controller
@RequestMapping("auto/dll")
public class AutoDllController {
    @Resource
    private DllService dllService;

    @ResponseBody
    @PostMapping("/createDll")
    public Map<String,Object> createDll(@Valid @RequestBody DllCreateForm dllCreateForm, BindingResult bindingResult){
        Map<String,Object> result = new HashMap<>();

        if (bindingResult.hasErrors()){
            String errMsg = bindingResult.getFieldError().getDefaultMessage();
            result.put("status",500);
            result.put("msg",errMsg);
            return result;
        }
        String mainId = dllService.createDll(dllCreateForm);
        if (mainId == null){
            result.put("status",500);
            result.put("msg","创建失败，请联系开发人员");
        }
        result.put("status",200);
        result.put("data",mainId);
        return result;
    }

    @GetMapping("/infoByMainId")
    public ModelAndView infoByMainId(@RequestParam String mainId){
        List<DllItem> dllItemList = dllService.getDllWithMainId(mainId);
        ModelAndView modelAndView = new ModelAndView("ma");
        if (dllItemList.size() > 0){
            StringBuffer buffer = new StringBuffer();
            String numberPwdFormat = "<span>%s----%s<span/></br>";
            for (DllItem dllItem : dllItemList) {
                String dllNumber = dllItem.getDllNumber();
                String dllPwd = dllItem.getDllPwd();
                String numberPwd = String.format(numberPwdFormat,dllNumber,dllPwd);
                buffer.append(numberPwd);
            }
            modelAndView.getModel().put("data", buffer.toString());
            return modelAndView;
        }
        modelAndView.getModel().put("data", "未发现该记录");
        return modelAndView;
    }
}
